package com.jwmp.rbac.util;

import com.jwmp.rbac.domain.Module;
import com.jwmp.rbac.domain.Permission;
import com.jwmp.rbac.service.IPermissionService;
import com.jwmp.rbac.service.impl.PermissionServiceImpl;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class PermissionUtil {
    private static IPermissionService permissionService = new PermissionServiceImpl();

    public static void main(String[] args) {
        permissionService.loadPremissionToDB("com.jwmp.base.web.servlet");
    }

    /**
     * 读取项目中所有权限对象内容，存入集合中
     * @param packageName 读取 SetPermission 注解的类所在包
     * @return
     */
    public static List<Permission> loadPremissionToList(String packageName){
        List<Permission> ps = new ArrayList<>();

        // 获取包下的所有类的全限定名
        List<String> strClzs = ClassUtils.getClazzNameByPackageName(packageName);
        try {
            for (String strClz : strClzs) {
                Class<?> clz = Class.forName(strClz);
                Method[] ms = clz.getMethods();
                for (Method m : ms) {
                    SetPermission setPermission = m.getAnnotation(SetPermission.class);
                    if (setPermission != null) {
                        ps.add(new Permission(setPermission.name(),setPermission.expression(),new Module(null,setPermission.moduleName(),null)));
                    }
                }
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return ps;
    }

    public static Boolean hasPermission(Long empId,String uri){
        List<Permission> permissionList = permissionService.selectListByEmpId(empId);
        List<String> expressionList = permissionList.stream().map(p -> p.getExpression()).collect(Collectors.toList());
        return expressionList.contains(uri);
    }
}
